<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>NodeTree</title>
    <!--引入css-->
    <!--Open Sans Font-->
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
    <!--Bootstrap Stylesheet [ REQUIRED ]-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
    <!--Nifty Stylesheet [ REQUIRED ]-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/nifty.css') }}">
    <!--FontAwesome [ DEMONSTRATION ]-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/font-awesome.min.css') }}">
    <!-- zTree -->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/zTree/css/awesomeStyle/awesome.css') }}">
    <!-- bees -->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bees.css') }}">

    <style>

        .treebox {
            position: relative;
        }

        .treebox #rMenu {
            position: absolute;
            left: 0;
            top: 0;
            cursor: pointer;
        }

    </style>

</head>
<body>
    <div id="container">
        <div class="treebox">
            <div id="nTree" class="ztree">
            </div>
            <div id="rMenu">
                <ul class="dropdown-menu menu-actions">
                    <li id="m_create" tabindex="-1" onclick="addTreeNode();"><a><i class="fa fa-plus-square-o"></i> 新建节点 </a></li>
                    <li id="m_update" tabindex="-1" onclick="editTreeNode();"><a><i class="fa fa-pencil-square-o"></i> 重命名节点 </a></li>
                    <li id="m_delete" tabindex="-1" onclick="removeTreeNode();"><a><i class="fa fa-minus-square"></i> 删除节点 </a></li>
                </ul>
            </div>
        </div>
    </div>
</body>

    <!--引入JavaScript-->
    <!--jQuery [ REQUIRED ]-->
    <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
    <!--BootstrapJS [ RECOMMENDED ]-->
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
    <!--NiftyJS [ RECOMMENDED ]-->
    <script src="{{ url_for('static', filename='js/nifty.js') }}"></script>
    <!--CsrfJS-->
    <script src="{{ url_for('static', filename='js/csrf.js') }}"></script>
    <!--zTree-->
    <script src="{{ url_for('static', filename='plugins/zTree/js/jquery.ztree.all.js') }}"></script>

    <!--bees-->
    <script src="{{ url_for('static', filename='js/bees.js') }}"></script>


    <script>
        var zTree, rMenu = null;
        var showMenu = false;

        function initNodeTree(options) {
            var treeUrl = '{{ url_for('assets.api-node-tree') }}?type=1';
            var setting = {
                view: {
                    dblClickExpand: false,
                    showLine: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                async: {
                    enable: true,
                    url: treeUrl,
                    autoParam: ["id=key", "name=n", "level=lv"],
                    type: 'get'
                },
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: true
                    }
                },
                callback: {
                    onRightClick: onRightClick,
                    beforeClick: beforeClick,
                    onRename: onRename,
                    onSelected: onSelected,
                    beforeDrag: beforeDrag,
                    onDrag: onDrag,
                    beforeDrop: beforeDrop,
                    onDrop: onDrop,
                    beforeAsync: defaultCallback("Before async")
                }
            };

            $.get(treeUrl, function (data, status) {
                zTree = $.fn.zTree.init($("#nTree"), setting, data);
                if (options.showMenu) {
                    showMenu = true;
                    rMenu = $("#rMenu");
                }
            });
        }

        function onBodyMouseDown(event){
            if (!(event.target.id === "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }

        function showRMenu(type, x, y) {
            var offset = $("#nTree").offset();
            var scrollTop = document.querySelector('.treebox').scrollTop;
            x -= offset.left;
            y -= offset.top + scrollTop;
            x += document.body.scrollLeft;
            y += document.body.scrollTop + document.documentElement.scrollTop;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
            $("#rMenu ul").show();
            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }

        function onRightClick(event, treeId, treeNode) {
            if (!showMenu) {
                return
            }
            if (!treeNode && event.target.tagName.toLowerCase() !== "button" && $(event.target).parents("a").length === 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }

        function addTreeNode() {
            hideRMenu();
            var parentNode = zTree.getSelectedNodes()[0];
            if (!parentNode){
                return
            }
            zTree.expandNode(parentNode, true, null, null); // 打开节点

            var url = "{{ url_for('assets.api-node-add-children', pk=default_pk) }}".replace(bees.defaultPK, parentNode.meta.node.id);
            setAjaxCSRFToken();
            $.post(url, {}, function (results){
                if (results.code === 200) {
                    var newNode = {
                        id: results.data.meta.node["key"],
                        name: results.data.meta.node["value"],
                        pId: parentNode.id,
                        meta: {
                            "node": results.data.meta.node
                        }
                    };
                    newNode.checked = zTree.getSelectedNodes()[0].checked;
                    zTree.addNodes(parentNode, 0, newNode); // 新增节点
                    var node = zTree.getNodeByParam('id', newNode.id, parentNode);
                    zTree.editName(node);

                    bees.tipSuccess({
                        message: '节点创建成功'
                    });
                } else {
                    bees.tipError({
                        message: '节点创建失败'
                    });
                }
            });
        }

        function removeTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }
            var current_node_id = current_node.meta.node.id;
            var url = "{{ url_for('assets.api-node-delete', pk=default_pk) }}".replace(bees.defaultPK, current_node_id);

            setAjaxCSRFToken();
            $.post(url, {}, function (results){
                if (results.code === 200) {
                    zTree.removeNode(current_node);
                    bees.tipSuccess({
                        message: '删除节点成功'
                    });
                } else if(results.code === 400){
                    bees.tipError({
                        message: results.data.message
                    });
                }else {
                    bees.tipError({
                        message: '删除节点失败'
                    });
                }
            });
        }

        function editTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }
            current_node.name = current_node.meta.node.value;
            zTree.editName(current_node);
        }

        function onRename(event, treeId, treeNode, isCancel) {
            var current_node_id = treeNode.meta.node.id;
            var url = "{{ url_for('assets.api-node-rename', pk=default_pk) }}".replace(bees.defaultPK, current_node_id);
            var data = {"value": treeNode.name};
            if (isCancel){
                return
            }

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    var assets_amount = treeNode.meta.node.assets_amount;
                    if (!assets_amount) {
                        assets_amount = 0;
                    }
                    treeNode.name = treeNode.name + ' (' + assets_amount + ')';
                    zTree.updateNode(treeNode);

                    bees.tipSuccess({
                        message: '重命名节点成功'
                    });
                } else {
                    bees.tipError({
                        message: '重命名节点失败'
                    });
                }
            });
        }

        function beforeDrop(treeId, treeNodes, targetNode, moveType) {
            var treeNodesNames = [];
            $.each(treeNodes, function (index, value) {
                treeNodesNames.push(value.name);
            });

            var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.name + "` 下吗?";
            return confirm(msg);
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {
            var treeNodesIds = [];
            $.each(treeNodes, function (index, value) {
                treeNodesIds.push(value.meta.node.id);
            });
            var url = "{{ url_for('assets.api-node-move-children', pk=default_pk) }}".replace(bees.defaultPK, targetNode.meta.node.id);
            var data = {nodes: JSON.stringify(treeNodesIds)};

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    bees.tipSuccess({
                        message: '移动节点成功'
                    });
                } else {
                    bees.tipError({
                        message: '移动节点失败'
                    });
                }
            });
        }

        function onSelected(event, treeNode) {
            console.log('onSelected');
        }

        function beforeClick() {
            return true;
        }

        function beforeDrag() {
            return true
        }

        function onDrag() {

        }

        function defaultCallback(action) {
            function logging() {
                console.log(action)
            }
            return logging
        }

        $(function () {
            initNodeTree({
                showMenu: true
            });
        });

    </script>

</html>